import util from './util'
import {
  CODE_OK
} from './config.js'

function checkUploadStatus(response) {
  if (response.statusCode === 200) {
    return response;
  }
  const error = new Error(response.statusCode);
  error.name = '出错啦！';
  error.response = response
  throw error;
}

// 请求
export default function request(options) {
  return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        success: function(res) {
          if (res.statusCode == 200 && res.data.code == 10000) {
            resolve(res)
          } else {
            console.log(res)
            util.showToast(res.msg || res.data.msg || '服务异常')
            reject(res)
          }
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
    .catch(err => {
      util.showToast(err.name || '请求失败')
    })
}

// 上传文件
export function uploadFile(options) {
  return new Promise((resolve, reject) => {
      wx.uploadFile({
        ...options,
        success: function(res) {
          resolve(res)
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
    .then(checkUploadStatus)
    .catch(err => {
      util.showToast(err.name || '请求失败')
    })
}